//
//  mathematics.hpp
//  VideoParse
//
//  Created by xiaerfei on 2020/5/1.
//  Copyright © 2020 erfeixia. All rights reserved.
//

#ifndef mathematics_hpp
#define mathematics_hpp
#include "intmath.hpp"
#include "common.hpp"
#include <stdlib.h>

namespace mathematics {
/* Stein's binary GCD algorithm:
 * https://en.wikipedia.org/wiki/Binary_GCD_algorithm */
inline int64_t av_gcd(int64_t a, int64_t b) {
    int za, zb, k;
    int64_t u, v;
    if (a == 0)
        return b;
    if (b == 0)
        return a;
    za = intmath::ff_ctzll_c(a);
    zb = intmath::ff_ctzll_c(b);
    k  = FFMIN(za, zb);
    u = llabs(a >> za);
    v = llabs(b >> zb);
    while (u != v) {
        if (u > v)
            FFSWAP(int64_t, v, u);
        v -= u;
        v >>= intmath::ff_ctzll_c(v);
    }
    return (uint64_t)u << k;
}
}


#endif /* mathematics_hpp */
